package com.hp.tiger.chapter4;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author XavierDong
 **/
public class ThreadLifeCycleObserver implements LifecycleListener {


    private static final Object LOCK = new Object();

    public void concurrentQuery(List<String> ids) {
        if (ids == null && ids.isEmpty())
            return;
        ids.stream().forEach(i -> new Thread(new ObserverableRunnable(this) {
            @Override
            public void run() {

                try {
                    notifyChange(new RunnableEvent(RunnableState.RUNNING, Thread.currentThread(), null));
                    System.out.println("query for the id " + i);
                    TimeUnit.SECONDS.sleep(1);
//                    int x = 1 / 0;
                    notifyChange(new RunnableEvent(RunnableState.DONE, Thread.currentThread(), null));
                } catch (Exception e) {
                    notifyChange(new RunnableEvent(RunnableState.ERROR, Thread.currentThread(), e));
                }

            }
        }, i).start());
    }

    @Override
    public void onEvent(ObserverableRunnable.RunnableEvent runnableEvent) {
        synchronized (LOCK) {
            System.out.println("The Runnable [" + runnableEvent.getThread().getName() + "] data changed and state is [" + runnableEvent.getState() + "]");
            if (runnableEvent.getCause() != null) {
                System.out.println("The Runnable [" + runnableEvent.getThread().getName() + "] process failed.");
                runnableEvent.getCause().printStackTrace();
            }
        }
    }


}
